package com.jrx.anytxn.param.job.bactchBillCompare.config;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.config.BillCompareConfig;
import com.jrx.anytxn.param.config.PathFileConfig;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.entity.TlBillTransCompareSummary;
import com.jrx.anytxn.param.entity.TlBillTransSummary;
import com.jrx.anytxn.param.mapper.ext.ExtTlBillTransCompareSummaryMapper;
import com.jrx.anytxn.param.mapper.ext.ExtTlBillTransDetilMapper;
import com.jrx.anytxn.param.mapper.ext.ExtTlBillTransInnerSummaryMapper;
import com.jrx.anytxn.param.mapper.ext.ExtTlBillTransSummaryMapper;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 核心对账-总分核对job
 *
 * @author : zcc
 * 2020/11/26
 */
@Configuration
@EnableConfigurationProperties(PathFileConfig.class)
public class BatchBillCompareConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(BatchBillCompareConfiguration.class);

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    private IOrganizationTableService organizationTableService;

    @Autowired
    private ISegmentService iSegmentService;

    @Resource
    private ExtTlBillTransSummaryMapper extTlBillTransSummaryMapper;

    @Resource
    private ExtTlBillTransDetilMapper extTlBillTransDetilMapper;

    @Resource
    private ExtTlBillTransCompareSummaryMapper extTlBillTransCompareSummaryMapper;

    @Resource
    private ExtTlBillTransInnerSummaryMapper extTlBillTransInnerSummaryMapper;
    @Resource
    private BillCompareConfig billCompareConfig;


    @Bean
    public Job billCompareJob() throws IOException {
        return jobBuilderFactory.get("billCompareJob")
                .start(billFileCompareStep()) //账务文件总分核对
                .next(billFileAndTXNCompareStep()) //账务文件与TXN系统总数核对
                .build();
    }

    @Bean
    public Step billFileCompareStep() throws IOException {
        return stepBuilderFactory.get("billFileCompareStep").tasklet(billFileCompareTasklet()).build();
    }

    @Bean
    public Tasklet billFileCompareTasklet() {
        return (stepContribution, chunkContext) -> {
            List<TlBillTransCompareSummary> tlBillTransCompareSummaryList = new ArrayList<>();
            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
            String businessDate = DateUtils.format(org.getToday());
            logger.info("账务文件总分核对开始。。。,业务日期为:{}", businessDate);
            //删除当日对账数据，支持重跑
            extTlBillTransCompareSummaryMapper.deleteByBusDate(org.getToday());

            //放款
            TlBillTransSummary tlBillTransSummary = extTlBillTransSummaryMapper.selectByTenantIdAndBusDateAndTransType(
                    org.getTenantId(), org.getToday(), Constant.TRANS_TYPE_FK);

            if(null != tlBillTransSummary){
                tlBillTransCompareSummaryList.add(buidBillTransCompareSummary(tlBillTransSummary, org, Constant.COMPARE_TYPE_0));
            }

            //还款
            tlBillTransSummary = extTlBillTransSummaryMapper.selectByTenantIdAndBusDateAndTransType(
                    org.getTenantId(), org.getToday(), Constant.TRANS_TYPE_HK);

            if(null != tlBillTransSummary){
                tlBillTransCompareSummaryList.add(buidBillTransCompareSummary(tlBillTransSummary, org, Constant.COMPARE_TYPE_0));
            }
            if (CollectionUtils.isNotEmpty(tlBillTransCompareSummaryList)){
                extTlBillTransCompareSummaryMapper.insertbatch(tlBillTransCompareSummaryList);
            }

            logger.info("账务文件总分核对结束。。。,业务日期为:{}", businessDate);
            return RepeatStatus.FINISHED;
        };
    }

    @Bean
    public Step billFileAndTXNCompareStep() {
        return stepBuilderFactory.get("billFileAndTXNCompareStep").tasklet(billFileAndTXNCompareTasklet()).build();
    }

    @Bean
    public Tasklet billFileAndTXNCompareTasklet() {
        return (stepContribution, chunkContext) -> {
            List<TlBillTransCompareSummary> tlBillTransCompareSummaryList = new ArrayList<>();
            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
            String businessDate = DateUtils.format(org.getToday());

            logger.info("账务文件与TXN系统总数核对开始。。。,业务日期为:{}", businessDate);

            //放款
            TlBillTransSummary tlBillTransSummary = extTlBillTransSummaryMapper.selectByTenantIdAndBusDateAndTransType(
                    org.getTenantId(), org.getToday(), Constant.TRANS_TYPE_FK);

            if(null != tlBillTransSummary){
                tlBillTransCompareSummaryList.add(buidBillTransCompareSummary(tlBillTransSummary, org, Constant.COMPARE_TYPE_1));
            }

            //还款
            tlBillTransSummary = extTlBillTransSummaryMapper.selectByTenantIdAndBusDateAndTransType(
                    org.getTenantId(), org.getToday(), Constant.TRANS_TYPE_HK);

            if(null != tlBillTransSummary){
                tlBillTransCompareSummaryList.add(buidBillTransCompareSummary(tlBillTransSummary, org, Constant.COMPARE_TYPE_1));
            }
            if (CollectionUtils.isNotEmpty(tlBillTransCompareSummaryList)){
                extTlBillTransCompareSummaryMapper.insertbatch(tlBillTransCompareSummaryList);
            }

            logger.info("账务文件与TXN系统总数核对结束。。。,业务日期为:{}", businessDate);
            return RepeatStatus.FINISHED;
        };
    }

    private TlBillTransCompareSummary buidBillTransCompareSummary(TlBillTransSummary tlBillTransSummary
            , PrOrganizationTable org, String compareType) throws SegmentException {

        Integer totalCount = 0;
        BigDecimal totalAmount = BigDecimal.ZERO;
        Integer successCount = 0;
        BigDecimal successAmount = BigDecimal.ZERO;
        String comDescPre = "";

        TlBillTransCompareSummary tlBillTransCompareSummary = new TlBillTransCompareSummary();
        if(Constant.COMPARE_TYPE_0.equals(compareType)){ //账务文件内部总分核对
            totalCount = Optional.ofNullable(extTlBillTransDetilMapper.countByTenantIdAndBusDateAndTransType(
                    org.getTenantId(), org.getToday(), tlBillTransSummary.getTransactionType())).orElse(0);

            totalAmount = Optional.ofNullable(extTlBillTransDetilMapper.sumByTenantIdAndBusDateAndTransType(
                    org.getTenantId(), org.getToday(), tlBillTransSummary.getTransactionType())).orElse(BigDecimal.ZERO);

            successCount = Optional.ofNullable(extTlBillTransDetilMapper.countByTenantIdBusDateAndTransStatusAndTransType(
                    org.getTenantId(), org.getToday(), Constant.COMPARE_FLAG_1,tlBillTransSummary.getTransactionType())).orElse(0);

            successAmount = Optional.ofNullable(extTlBillTransDetilMapper.sumByTenantIdBusDateAndTransStatusAndTransType(
                    org.getTenantId(), org.getToday(),Constant.COMPARE_FLAG_1,tlBillTransSummary.getTransactionType())).orElse(BigDecimal.ZERO);
            comDescPre = "[账务文件内部总分核对]";

        } else if(Constant.COMPARE_TYPE_1.equals(compareType)){ //账务文件总数与TXN总数核对
            totalCount = Optional.ofNullable(extTlBillTransInnerSummaryMapper.countByTenantIdAndBusDateAndBillType(
                    org.getTenantId(), org.getToday(), tlBillTransSummary.getTransactionType())).orElse(0);

            totalAmount = Optional.ofNullable(extTlBillTransInnerSummaryMapper.sumByTenantIdAndBusDateAndBillType(
                    org.getTenantId(), org.getToday(), tlBillTransSummary.getTransactionType())).orElse(BigDecimal.ZERO);

            successCount = Optional.ofNullable(extTlBillTransInnerSummaryMapper.countByTenantIdBusDateAndInnerStatusAndBillType(
                    org.getTenantId(), org.getToday(), Constant.TRANSFER_SUM_STATUS_S, tlBillTransSummary.getTransactionType(),billCompareConfig.getThirdChannel())).orElse(0);

            successAmount = Optional.ofNullable(extTlBillTransInnerSummaryMapper.sumByTenantIdBusDateAndInnerStatusAndBillType(
                    org.getTenantId(), org.getToday(),Constant.TRANSFER_SUM_STATUS_S, tlBillTransSummary.getTransactionType(),billCompareConfig.getThirdChannel())).orElse(BigDecimal.ZERO);

            comDescPre = "[账务文件总数与TXN总数核对]";
        }

        tlBillTransCompareSummary.setId(iSegmentService.getId("TlBillTransCompareSummary"));
        tlBillTransCompareSummary.setTenantId(org.getTenantId());
        tlBillTransCompareSummary.setOrganizationId(org.getOrganizationId());
        tlBillTransCompareSummary.setBillType(tlBillTransSummary.getTransactionType());
        tlBillTransCompareSummary.setCompareType(compareType);
        tlBillTransCompareSummary.setSummaryTotalCount(tlBillTransSummary.getTotalCount());
        tlBillTransCompareSummary.setSummaryTotalAmount(tlBillTransSummary.getTotalAmount());
        tlBillTransCompareSummary.setSummarySuccessCount(tlBillTransSummary.getSuccessCount());
        tlBillTransCompareSummary.setSummarySuccessAmount(tlBillTransSummary.getSuccessAmount());
        tlBillTransCompareSummary.setDetailTotalCount(totalCount);
        tlBillTransCompareSummary.setDetailTotalAmount(totalAmount);
        tlBillTransCompareSummary.setDetailSuccessCount(successCount);
        tlBillTransCompareSummary.setDetailSuccessAmount(successAmount);
        tlBillTransCompareSummary.setBusinessDate(org.getToday());

        Integer transSumTotalCount = Optional.ofNullable(tlBillTransSummary.getTotalCount()).orElse(0);
        BigDecimal transSumTotalAmount =  Optional.ofNullable(tlBillTransSummary.getTotalAmount()).orElse(BigDecimal.ZERO);
        Integer transSumSuccessCount =  Optional.ofNullable(tlBillTransSummary.getSuccessCount()).orElse(0);
        BigDecimal transSumSuccessAmount =  Optional.ofNullable(tlBillTransSummary.getSuccessAmount()).orElse(BigDecimal.ZERO);

        if(!transSumTotalCount.equals(totalCount) || transSumTotalAmount.compareTo(totalAmount) != 0
                || !transSumSuccessCount.equals(successCount) || transSumSuccessAmount.compareTo(successAmount) != 0){
            tlBillTransCompareSummary.setCompareStatus(Constant.COMPARE_FLAG_0);
            tlBillTransCompareSummary.setCompareDesc(comDescPre+"账不平");
        } else {
            tlBillTransCompareSummary.setCompareStatus(Constant.COMPARE_FLAG_1);
            tlBillTransCompareSummary.setCompareDesc(comDescPre+"账平");
        }
        return tlBillTransCompareSummary;
    }

}